package com.niannian.service;

import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 自动读取短信
 * 
 */
public class SmsContent {

	/**
	 * 发短信的号码
	 */
	private static final String NIANNIAN_SMS_NUM = "1069023660020477";// 注册
	private static final String NIANNIAN_SMS_NUM1 = "106575009553751";// 忘记密码
	/**
	 * 短信收件箱uri
	 */
	private static final Uri INBOX_URI = Uri.parse("content://sms/inbox");
	private static final int WAHT_ONCHANGE = 61515;

	/**
	 * 创建服务的Activity
	 */
	private Activity activity;
	/**
	 * 验证码输入框
	 */
	private EditText editText;

	/**
	 * 构造器
	 * 
	 * @param activity
	 *            创建服务的Activity
	 * @param editText
	 *            验证码输入框
	 */
	public SmsContent(Activity activity, EditText editText) {
		this.activity = activity;
		this.editText = editText;
		activity.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, observer);
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == WAHT_ONCHANGE) {
				String sms = getSmsInfo();
				editText.setText(sms);
				if (sms.matches("[\\d]{6}")) {
					Toast.makeText(activity, "已经自动为您填写验证码。", Toast.LENGTH_SHORT).show();
				}
			}
			// 解除观察者
			activity.getContentResolver().unregisterContentObserver(observer);
		}
	};

	private ContentObserver observer = new ContentObserver(handler) {
		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			handler.sendEmptyMessage(WAHT_ONCHANGE);
		}
	};

	/**
	 * 获取短信验证码
	 */
	private String getSmsInfo() {
		String[] projection = new String[] { "_id", "address", "body" };
		@SuppressWarnings("deprecation")
		Cursor cusor = activity.managedQuery(INBOX_URI, projection, null, null, "date desc");
		int phoneNumberColumn = cusor.getColumnIndex("address");
		int smsbodyColumn = cusor.getColumnIndex("body");
		if (cusor != null) {
			while (cusor.moveToNext()) {
				String numb = cusor.getString(phoneNumberColumn);
				String body = cusor.getString(smsbodyColumn);
				if (NIANNIAN_SMS_NUM.equals(numb)) {
					cusor.close();
					return body.substring(4, 10);
				}
			}
			cusor.close();
		}
		return "";
	}

}
